package com.zrf.kafka.main;

import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.producer.*;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.apache.kafka.common.serialization.StringSerializer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutionException;

/**
 * @author zhouruifeng
 * @date 2018/5/17
 */
public class Main {
    private static final Logger LOGGER = LoggerFactory.getLogger(Main.class);

    public static void main(String[] args) {
        /*KfkProducer producerThread = new KfkProducer(KfkConfig.topic);
        producerThread.start();*/
        KfkConsumer consumerThread = new KfkConsumer(KfkConfig.topic);
        consumerThread.start();
//        testSend();
    }

    private static void testSend() {
        Map<String, Object> props = new HashMap<>();
        props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, KfkConfig.kafkaServerURL);
        props.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, false);
        props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
        props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
        props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "latest");
        props.put(ConsumerConfig.GROUP_ID_CONFIG, KfkConfig.groupId);
        Producer<String, String> producer = new KafkaProducer(props, new StringSerializer(), new StringSerializer());
//        producer = new MockProducer<>(true, new StringSerializer(), new StringSerializer());

        for (int i = 0; i < 100; i++) {
            try {
                producer.send(new ProducerRecord(KfkConfig.topic, Integer.toString(i), Integer.toString(i)), (RecordMetadata r, Exception e) -> {
                    if (e != null) {
                        LOGGER.error("系统异常:", e);
                    }
                }).get();
                System.out.println(String.format("send key: %s, send value: %s", Integer.toString(i), Integer.toString(i)));
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
        }

        producer.close();
    }
}
